
/**
 * @file	timer.c
 * @brief
 * @author
 * @date
 * @note
 * @see
 * @version $Id$
**/

#include <time.h>
#include <strings.h>

#include "timer.h"

#define DEF_TIMERMAX 	128

struct timer_t
{
	int num;
	time_t runtm;
	time_t interval;		// 可能是秒.
	timer_handler_t handler;
	void *arg;
};

int timer_cnt;
int timer_magic;
struct timer_t timer_list[DEF_TIMERMAX];

// 初始化计时器.
int timer_init()
{
	timer_cnt = 0;
	timer_magic = 0;

	return 0;
}

// 添加一计时器.
int timer_add(int interval, timer_handler_t handler, void *arg)
{
	if(timer_cnt >= DEF_TIMERMAX) {
		return -1;
	}

	timer_list[timer_cnt].num = ++timer_magic;
	timer_list[timer_cnt].runtm = (int)time(NULL);
	timer_list[timer_cnt].interval = interval;
	timer_list[timer_cnt].handler = handler;
	timer_list[timer_cnt].arg = arg;

	timer_cnt++;

	return timer_magic;
}

// 删除一计时器.
int timer_del(int num)
{
	int i=0;

	for(i=0; i<timer_cnt; i++) {
		if(timer_list[i].num == num) {
			bcopy(&timer_list[i], &timer_list[timer_cnt], sizeof(struct timer_t));
			timer_cnt--;

			break;
		}
	}

	return 0;
}

// 运行计时器.
int timer_exec()
{
	int i;
	time_t curtime = time(NULL);

	for(i=0; i<timer_cnt; i++) {
		if(timer_list[i].runtm + timer_list[i].interval <= curtime) {
			timer_list[i].handler(timer_list[i].arg);
			timer_list[i].runtm = curtime;

			break;
		}
	}

	return 0;
}

